﻿var DGON_DOTNET = DGON_DOTNET || {};

; (function($, log, undefined) {
	DGON_DOTNET.Sortable =
	{
		makeSortable: function (tableSelector, options) {
			options = optionsWithDefaults(options, {
				handleSelector: '.handle',
				deleteSelector: '.trash',
				deletedSelector: '.data-delete',
				sortSelector: '.data-short'
			});
			
			var tbody = $(tableSelector + ' tbody');
			$(tbody).sortable({
				helper: maintainWidth,
				handle: options.handleSelector,
				stop: function (e, ui) {
					reorder(e.target.rows, options.sortSelector);
				}
			});
		}
	};
	function optionsWithDefaults(options, defaults) {
		if (typeof options === 'object') {
			options = $.extend(defaults, options);
		}
		else {
			options = defaults;
		}
		return options;
	}
	
	var maintainWidth = function (e, ui) {
		ui.children().each(function () {
			$(this).width($(this).width());
		});
		return ui;
	};
	function reorder(rows, sortSelector) {
		$(rows).each(function (index) {
			var $row = $(this);
			$row.find(sortSelector).val(index);
		});
	}

})(jQuery);